#ifndef HTTPPOOL_H__
#define HTTPPOOL_H__


#include "Interface.h"


class CriticalSection;
class CHttpPool :public ICallBack,public CWinThread
{
public:
	static CHttpPool* GetInstance()
	{
		static CHttpPool sObj;
		return &sObj;
	}


	virtual ~CHttpPool(void);

	void Init(int nCount);
	void Init_in(int nCount);

	bool AddTask(IRecv* pRecv,const char * pBuf,int nLen,const CString& strHost,int nPort);
	bool AddUrl(IRecv* pRecv,const CString& strUrl);
	bool AddPostUrl(IRecv* pRecv,const CString& strUrl,const char* pPostBuf,int nLen);
	bool AddPostUrl2(IRecv* pRecv,const CString& strUrl,const char* pPostBuf,int nLen);
	bool AddRangeUrl(IRecv* pRecv,const CString& strUrl,LONGLONG dwBegin);
	bool AddRangeUrl(IRecv* pRecv,const CString& strUrl,LONGLONG dwBegin,LONGLONG dwEnd);

	bool Stop();
	bool Start();
	bool Pause();
	bool Resume();

	virtual void DoSetContentCoding(CWorkItem*,const string&);
	virtual void DoCallBack(CWorkItem*,char*,int);
	virtual void OnClose(CWorkItem*);
	virtual void OnSendData(CWorkItem*);
	virtual void Process();
	virtual void DoSetContentLength(CWorkItem*,int);
	virtual void DoSetContentRange(CWorkItem*,const string&);

	bool StopWorkItem(IRecv* pRecv);

protected:

	CHttpPool(void);
	CWorkItem* GetCurFreeItem();
	void SetItem(CWorkItem*,HttpTaskData*);
	HttpTaskData* GetItemData(CWorkItem*);
	void DelItemData(CWorkItem*);
	void ClearItem();
	int GetItemSize();
	bool CloseWorkItem(IRecv* pRecv);

	void PushBackTask(HttpTaskData *);
	HttpTaskData * GetFrontTask();
	void	PopTask();
	void	ClearTask();
	int		GetTaskSize();
	
	
	static UINT ThreadFunction(LPVOID lpData);	

	virtual void SendData(CWorkItem* );

	void StopAll();

	HttpStatus GetHttpStatus();
	void SetHttpStatus(HttpStatus nStatus);

	queue<HttpTaskData*> m_qTaskDatas;
	CriticalSection * m_pTaskSection;

	void ActiveProcess();

	virtual void OnSockClose(CWorkItem*);


	CriticalSection * m_pMapSection;
	map<CWorkItem*,HttpTaskData*>	m_mapRecvs;
private:

	CWinThread * m_pWinThread;
	int m_nPoolSize; 

	HttpStatus m_nHttpStatus;
	CriticalSection * m_pStatusSection;
};
#endif